//
//  YXYStrollCollectionViewCell.m
//  Topit
//
//  Created by dllo on 15/12/3.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "YXYStrollCollectionViewCell.h"
#import "YXYStrollImageCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
@implementation YXYStrollCollectionViewCell

- (void)dealloc {
    [_flowLayout release];
    [_collectionView release];
    [_dataSource release];
    _strollDelegate = nil;
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
        self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[YXYStrollImageCollectionViewCell class] forCellWithReuseIdentifier:@"YXYStrollImageCollectionViewCellIdentifier"];
        //添加头部刷新
        [self addheader];
//        //添加尾部刷新
//        [self addfooter];
        [self addSubview:self.collectionView];
        [self getDate];
        [_flowLayout release];
        [_collectionView release];
      
    }
    return self;
}

#pragma mrak - 网络请求
- (void)getDate {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.labelText = @"正在加载";
    hud.mode = MBProgressHUDModeIndeterminate;
    [YXYNetWorkTool getWithUrl:kStrollGETURl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        for (NSDictionary *dic in result[@"item"]) {
            YXYStrollModel *strollModle = [[YXYStrollModel alloc] initWithDictionary:dic];
            [_dataSource insertObject:strollModle atIndex:0];
            [strollModle release];
        }
        [hud hide:YES afterDelay:1];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_collectionView reloadData];
        });
    } fail:^(NSError *error) {
        [hud hide:YES];
        [ProgressHUD showError:@"请检查网络"];
    }];
}

- (void)getFoot {
    [self.collectionView addFooterWithCallback:^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
        hud.labelText = @"正在加载";
        hud.mode = MBProgressHUDModeIndeterminate;
        self.number += 30;
        NSString *num = [NSString stringWithFormat:@"%ld", _number];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:num, @"offset", nil];
        [YXYNetWorkTool getWithUrl:kStrollGETURl parameter:dic httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            if ([result[@"item"] isKindOfClass:[NSArray class]]) {
                for (NSDictionary *dic in result[@"item"]) {
                    YXYStrollModel *strollModle = [[YXYStrollModel alloc] initWithDictionary:dic];
                    [_dataSource addObject:strollModle];
                    [strollModle release];
                }
            }else {
                [ProgressHUD showSuccess:@"亲爱的已经到底er了"];
            }
            [hud hide:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_collectionView reloadData];
                [_collectionView footerEndRefreshing];
            });
        } fail:^(NSError *error) {
            [hud hide:YES];
            [ProgressHUD showError:@"请检查网络"];
        }];
    }];

}



-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {

    CGFloat kWidth = self.frame.size.width / 2;
    CGFloat kHeight = (self.frame.size.height - 120) / 3;
    _flowLayout.itemSize = CGSizeMake(kWidth, kHeight);
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.minimumLineSpacing = 0;
    _collectionView.frame = CGRectMake(0, 60, self.frame.size.width, self.frame.size.height - 104);
}

#pragma mark - CollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    YXYStrollImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YXYStrollImageCollectionViewCellIdentifier" forIndexPath:indexPath];
    YXYStrollModel *strollModel = _dataSource[indexPath.item];
    [cell.images sd_setImageWithURL:[NSURL URLWithString:strollModel.icon[@"url"]] placeholderImage:[UIImage imageNamed:@"empty@2x"]];
    if ([passWord isEqualToString:@"Night"]) {
        cell.backgroundColor = [UIColor blackColor];
    }else {
        cell.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}

#pragma mark - 刷新
- (void)addheader {
    [_collectionView addHeaderWithCallback:^{
        
        [self getDate];
        [_dataSource removeAllObjects];
        [_collectionView reloadData];
        [_collectionView headerEndRefreshing];
    }];
}


#pragma mark - scrollView
//判断是否滑动到底部，当滑动到底部时 刷新数据
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.bounds;
    CGSize size = scrollView.contentSize;
    UIEdgeInsets inset = scrollView.contentInset;
    CGFloat currentOffset = offset.y + bounds.size.height - inset.bottom;
    CGFloat maximumOffset = size.height;

    if (currentOffset == maximumOffset) {
        [self getFoot];

    }
    if (currentOffset == 14980) {
        UIAlertView *allert = [[UIAlertView alloc] initWithTitle:@"别滑了" message:@"屁股疼" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [allert show];

    }
}

#pragma mark - 点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    YXYStrollModel *strollModel = _dataSource[indexPath.item];
    [self.strollDelegate strollDelegateWithURl:strollModel.next];
}

@end
